package stardust.product.utils.tiantiankuaidi;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.htmlparser.Node;
import org.htmlparser.Parser;
import org.htmlparser.Tag;
import org.htmlparser.nodes.TagNode;
import org.htmlparser.nodes.TextNode;
import org.htmlparser.util.NodeIterator;
import org.htmlparser.util.ParserException;
import stardust.core.java.thread.FixedThreadPool;
import stardust.core.network.protocol.http.HttpClient;
import stardust.core.network.protocol.http.HttpMethod;
import stardust.core.network.protocol.http.HttpResponseMeta;
import stardust.core.support.db.DataAccessObject;


public class TTKD
{

  public static final String QUERY_URL = "http://122.224.96.3/donet/query.aspx?wen=";

  public static final int POOL_SIZE = 32;

  public static final FixedThreadPool pool = new FixedThreadPool("", POOL_SIZE, POOL_SIZE);

  public static String getOrderNo()
  {
    DataAccessObject dao = TianTianKuaiDiDB.getDataAccessObject();
    
    try
    {
      return dao.get("SELECT TRIM(TO_CHAR(TIAN_TIAN_KUAI_DI_SEQ.NEXTVAL, '000000000000')) SEQ FROM DUAL").get("SEQ").toString();
    }
    finally
    {
      dao.close(true);
    }
  }
  
  public static void saveOrderInfo(String orderNo, List<String> times, List<String> msgs)
  {
    DataAccessObject dao = TianTianKuaiDiDB.getDataAccessObject();
    
    try
    {
      for (int i = 0; i < times.size(); i++)
      {
        dao.execute("INSERT INTO TIAN_TIAN_KUAI_DI VALUES (?, ?, ?)", orderNo, times.get(i), msgs.get(i));
      }
      
      dao.close(false);
    }
    finally
    {
      dao.close(true);
    }
  }
  
  public static void main(String[] args) throws InterruptedException
  {
    for (int i = 0; i < POOL_SIZE; i++)
    {
      pool.run(new Fetcher());
    }

    while (true)
    {
      Thread.sleep(1000);
    }
  }

  public static class Fetcher implements Runnable
  {

    public void run()
    {
      String orderNo = TTKD.getOrderNo();
      HttpClient http = new HttpClient("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.20 Safari/537.36");

      try
      {
        HttpResponseMeta rsp = http.go(TTKD.QUERY_URL + orderNo, HttpMethod.get);

        Parser parser;
        List<String> times = new ArrayList<String>();
        List<String> msgs = new ArrayList<String>();

        try
        {
          parser = Parser.createParser(new String(rsp.getData(), "GB2312"), "GB2312");

          Node n;
          Tag t;
          NodeIterator html = parser.elements();
          NodeIterator body;
          NodeIterator table;
          NodeIterator tr;
          NodeIterator td;

          while (html.hasMoreNodes())
          {
            n = html.nextNode();
            if (n instanceof TextNode) continue;
            t = (Tag) n;

            if (t.getTagName().equalsIgnoreCase("html"))
            {
              body = n.getChildren().elements();

              while (body.hasMoreNodes())
              {
                n = body.nextNode();
                if (n instanceof TextNode) continue;
                t = (Tag) n;

                int tableIndex = 0;

                if (t.getTagName().equalsIgnoreCase("body"))
                {
                  table = n.getChildren().elements();
                  
                  while (table.hasMoreNodes())
                  {
                    n = table.nextNode();
                    if (n instanceof TextNode) continue;
                    t = (Tag) n;
  
                    if (t.getTagName().equalsIgnoreCase("table"))
                    {
                      if (tableIndex++ == 1)
                      {
                        tr = n.getChildren().elements();
  
                        while (tr.hasMoreNodes())
                        {
                          n = tr.nextNode();
                          if (n instanceof TextNode) continue;
                          t = (Tag) n;
                          
                          if (t.getTagName().equalsIgnoreCase("tr"))
                          {
                            td = n.getChildren().elements();
                            
                            while (td.hasMoreNodes())
                            {
                              n = td.nextNode();
                              if (n instanceof TextNode) continue;
                              t = (Tag) n;
                              
                              if (t.getTagName().equalsIgnoreCase("td"))
                              {
                                if (times.size() <= msgs.size())
                                {
                                  times.add(toHtml(t.getChildren().elements()));
                                }
                                else
                                {
                                  msgs.add(toHtml(t.getChildren().elements()));
                                }
                              }
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }

          times.remove(0);
          msgs.remove(0);
          TTKD.saveOrderInfo(orderNo, times, msgs);
          
          System.out.println(orderNo + " - " + "成功");
        }
        catch (IOException e)
        {
          System.out.println(orderNo + " - " + e);
        }
        catch (ParserException e)
        {
          e.printStackTrace();
        }
        finally
        {
          http.disconnect();
        }
      }
      catch (IOException e)
      {
        e.printStackTrace();
      }
      finally
      {
        TTKD.pool.run(this);
      }
    }
    
    public static String toHtml(NodeIterator ns) throws ParserException
    {
      Node n;
      TagNode tag;
      TextNode txt;
      String str = "";
      
      while (ns.hasMoreNodes())
      {
        n = ns.nextNode();
        
        if (n instanceof TagNode)
        {
          tag = (TagNode) n;
          str += tag.toPlainTextString().trim();
        }
        else if (n instanceof TextNode)
        {
          txt = (TextNode) n;
          str += txt.getText().trim();
        }
      }
      
      return str;
    }

  }
  
}
